module Handler.News
    ( getNewsListR
    , postNewsListR
    , getNewsR
    , getNewsByTitleR
    )
where
 
import Import
import Data.Monoid()
import Yesod.Form.Nic (nicHtmlField)

entryForm :: Form News
entryForm = renderDivs $ News
    <$> areq textField "Title" Nothing
    <*> areq nicHtmlField "Content" Nothing


getNewsListR :: Handler RepHtml
getNewsListR = do
    newsList <- runDB $ selectList [] [Desc NewsTitle]
    (newsWidget, enctype) <- generateFormPost entryForm
    defaultLayout $ do
        $(widgetFile "newslist")

postNewsListR :: Handler RepHtml
postNewsListR = do
    ((res,newsWidget), enctype) <- runFormPost entryForm
    case res of
        FormSuccess news -> do
            newsId <- runDB $ insert news
            setMessage $ toHtml $ (newsTitle news) <> " created"
            redirect $ NewsR newsId
        _ -> defaultLayout $ do
            setTitle "Please correct your entry form"
            $(widgetFile "newsAddError")

getNewsR :: NewsId -> Handler RepHtml
getNewsR newsId = do
    news <- runDB $ get404 newsId
    defaultLayout $ do
        setTitle $ toHtml $ newsTitle news
        $(widgetFile "news")

getNewsByTitleR :: Text -> Handler RepHtml
getNewsByTitleR title = do
    
    maybeNews <- runDB $ selectFirst [NewsTitle ==. title] []
    case maybeNews of
        Just (Entity _ news) -> defaultLayout $ do
            $(widgetFile "news")
        Nothing -> error "not found"
